<template>
  <div>
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="updateSuccess"
    />

    <div class="field-warp">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'

export default {
  name: 'UpdateName',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      localName: this.value
    }
  },
  methods: {
    async updateSuccess() {
      this.$toast.loading({
        message: '更新中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 展示时长 值为 0 时，toast 不会消失
      })

      try {
        if (!this.localName) {
          // 如果用户没有输入内容
          return this.$toast('昵称不能为空')
        }

        await updateUserProfile({
          name: this.localName
        })

        // 更新视图
        this.$emit('input', this.localName)
        // 关闭弹窗
        this.$emit('close')
        // 提示消息
        this.$toast.success('更新成功')
      } catch (error) {
        this.$toast.fail('更新失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.van-nav-bar {
  background-color: #fff;
  /deep/.van-nav-bar__title,
  /deep/.van-nav-bar__text {
    color: #000;
  }
}

.field-warp {
  padding: 20px;
}
</style>
